package org.juggers.component;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.NoResultException;

import org.juggers.domain.Jugger;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author <a href="mailto:michel@breizhjug.org">Michel DAVID</a>
 */
@Service( "userDetailsProvider" )
public class DefaultUserDetailsProvider
    implements UserDetailsService
{

    @Override
    public UserDetails loadUserByUsername( String username )
        throws UsernameNotFoundException, DataAccessException
    {
        Jugger jugger = null;
        try
        {
            jugger = Jugger.findByEMail( username );
        }
        catch ( NoResultException ex )
        {
            throw new UsernameNotFoundException( "User " + username + " not found" );
        }

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for ( String role : jugger.getRoles() )
        {
            authorities.add( new GrantedAuthorityImpl( role ) );
        }

        return new User( username, jugger.getPassword(), !jugger.isPending(), true, true, true,
                         (GrantedAuthority[]) authorities.toArray(new GrantedAuthorityImpl[authorities.size()]) );
    }
}
